<template>
	<view>
    <u-navbar @leftClick="leftClick" :placeholder="true">
    </u-navbar>
    <view class="scan-code warp" v-if="outOfStockItems.length <= 0">
      <image class="iot" :src="iotIcon" mode=""></image>
      <u-button @click="oneClickReplenishment()" :customStyle="confirmBtnCustomStyle" text="扫设备二维码"></u-button>
    </view>
    <view v-else>
      <view class="restocking-list">
        <view class="cargo-lane" v-for="(item,index) in outOfStockItems" :key="index">
          <u--image class="product-picture"  width="180rpx" height="180rpx" :src="imgURL + item.fileName"></u--image >
          <view style="position: absolute">
            <view class="seal">
              <view class="seal-son">
                <span class="seal-span">缺货</span>
              </view>
            </view>
          </view>
         <view class="product-information">
           <view>货道:{{item.hierarchy}}0{{item.freightLane}}</view>
           <view>商品:{{item.commodityName}}</view>
         </view>
        </view>
      </view>
      <u-tabbar :value="tabBarIndex" :fixed="true" :placeholder="true" :safeAreaInsetBottom="true" :border="false">
        <view class="buttonBox">
          <u-button class="buttonBox-button" :customStyle="{ width:'300rpx'}" @click="reScanTheCode()" type="primary" shape="circle" text="重新扫码"></u-button>
          <u-button class="buttonBox-button" :customStyle="{ width:'300rpx'}" @click="ok()" type="primary" shape="circle" text="确定补货"></u-button>
        </view>
      </u-tabbar>
    </view>
    <u-popup :show="replenishmentResultsDisplay" mode="center" :round="20" :safeAreaInsetBottom="false" @touchmove.stop.prevent="moveHandle">
      <view class="expireDeviceBox" style="max-width: 600rpx">
        <view style="padding: 30rpx 60rpx;">
          <view class="expireDeviceBoxTitle">
            一键补货成功！
          </view>
          <view style="margin-top: 10rpx;text-align: center">
            <view v-for="(item,index) in restockingResults" :key="index" style="margin-bottom: 20rpx;">
              <text>{{ item.hierarchy }}层</text>
              <text>{{ item.freightLane }}列：</text>
              <text>补货前库存0，补货后库存{{item.stock}}</text>
            </view>
          </view>
          <view style="font-weight: 700;color: red;">如补货与实际补货数不符合，请前往补货上架手动修改</view>
        </view>
        <view class="expireDeviceBoxBottomBox">
<!--          <view @click="goToReplenishmentManagement()" class="expireDeviceBoxButtomBox-2">-->
<!--            前往-->
<!--          </view>-->
          <view @click="replenishmentResultsDisplay=false" class="expireDeviceBoxButtomBox">
            确定
          </view>
        </view>
      </view>
    </u-popup>
	</view>
</template>

<script>
  import { eventBus } from '@/main.js'
	export default {
		data() {
			return {
        imgURL: this.$configPath.imgURL,
        confirmBtnCustomStyle:{
          width: '487rpx',
          height: '88rpx',
          background: 'rgb(96, 114, 255)',
          borderRadius: '120px',
          color: '#fff',
          marginTop:'60rpx',
        },
        iotIcon: this.$configPath.staticFileUrl + '/image/home/iot.png',
        connectionStatus:-1,
        replenishmentResultsDisplay:false,
        restockingResults: [],
        outOfStockItems: [],
        state:2,
        tabBarIndex:0,
        deviceNo:null,
        isReturnAllowed:false,
			}
		},
    created() {
      // 监听事件
      eventBus.$on('connectionStatus', this.handleEventConnectionStatus)
    },
    onLoad(options) {
      if (options.isReturnAllowed){
          this.isReturnAllowed = options.isReturnAllowed;
      }
    },
		methods: {
      handleEventConnectionStatus(connectionStatus) {
        console.log('connectionStatus变化',connectionStatus)
        this.connectionStatus = connectionStatus;
      },
      leftClick() {
        if (this.isReturnAllowed){
            uni.navigateBack();
        }
      },
      goToReplenishmentManagement(){
        this.replenishmentResultsDisplay = false;
        uni.navigateTo({
          url: "/pages-vending-machine/restock/devices-restock?id=" + this.restockingResults[0].deviceId,
        })
      },
      oneClickReplenishment(){
        uni.showLoading({
          title: "正在调起...",
          mask: true
        })

        var that = this;
        uni.scanCode({
          success: function (res) {
            uni.hideLoading();
            let array = res.result.split("deviceNo/");

            let deviceNo = null;
            if (array.length != 2) {
              const params = that.$helpers.getUrlParams(res.result);
              if (params.d) {
                deviceNo = params.d;
              } else {
                getApp().err('二维码不规范_1：' + res.result);
                return;
              }
            } else {
              // 将扫一扫的结果转化成int类型
              try {
                deviceNo = array[1];
              } catch (e) {
                // console.log("-----转化设备号捕获到异常-------" + e)
                getApp().err('转化设备号捕获到异常：' + e);
                return;
              }
            }

            if (deviceNo == null || deviceNo == '') {
              // console.log("------转化结果有误------" + deviceNo)
              that.$helpers.toast('转化结果有误：' + deviceNo);
              return;
            }
            that.deviceNo = deviceNo;
            //连接
            that.findOutOfStockItems(deviceNo);
            //监听
            that.$bluetooth.startBLEConnectionStateListening(deviceNo);
          },
          fail: function() {
            uni.hideLoading();
          }
        });
      },

      findOutOfStockItems(deviceNo){
        this.$api('device.findOutOfStockItems',{'deviceNo':deviceNo}).then(res => {
          if (res.status == 0) {
              this.outOfStockItems = res.data;
              this.$bluetooth.initBluetooth(deviceNo, true);
          } else {
            this.$helpers.toast(res.msg);
          }
        })
      },
      reScanTheCode(){
        this.$bluetooth.closeBluetoothAdapter();
        this.oneClickReplenishment();
      },
      ok(){
        var that = this;
        if (this.connectionStatus === 2){
            that.$api('device.bluetoothOneClickReplenishment',{'deviceNo':this.deviceNo}).then(res => {
              if (res.status == 0) {
                that.restockingResults = res.data;
                that.replenishmentResultsDisplay = true;
              } else {
                that.$helpers.toast(res.msg);
              }
            })
        }else if (this.connectionStatus === 3){
          uni.showModal({
            title: '提示',
            cancelText:'知道了',
            confirmText:'退出',
            content: '蓝牙未连接上设备，请确保蓝牙为打开状态再"重新扫码"或选择"退出"重新进入再扫码',
            success: function (res) {
              if (res.confirm) {
                  wx.exitMiniProgram({})
              }
            }
          })
        }else if (this.connectionStatus === 1){
          this.$helpers.toast("正在连接设备中...");
        }
      },
    }
	}
</script>

<style lang="scss">
  .buttonBox{
    width: 100%;
    padding: 0rpx 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .seal {
    width: 160rpx;
    height: 160rpx;
    border: solid 6rpx #B4B4B4;
    border-radius: 100%;
    background-color: rgba(255, 255, 255, 0.5);
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    bottom: -10rpx;
  }

  .seal-son {
    width: 145rpx;
    height: 145rpx;
    border: solid 2rpx #B4B4B4;
    border-radius: 100%;
    background-color: rgba(255, 255, 255, 0.5);
    position: relative;

    .seal-span {
      position: absolute;
      top: 47rpx;
      text-align: center;
      font-size: 35rpx;
      transform: rotate(-35deg);
      right: 40rpx;
      color: #B4B4B4;
      font-weight: 900;
    }
  }
  .restocking-list{
    padding: 20rpx;
    display: grid;
    grid-row-gap: 20rpx;
    grid-template-columns: repeat(2, auto);
    justify-content: space-around;
    align-content: center;
    .cargo-lane{
      width: 300rpx;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: space-between;
      background-color: #FFFFFF;
      padding: 20rpx;
      border-radius: 20rpx;
      .product-information{
        width: 100%;
        margin-top: 20rpx;
      }
      .product-picture{
        width: 100rpx;
        height: 100rpx;
      }
    }
  }
  .warp{
    //height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;

    .iot{
      width: 328rpx;
      height: 538rpx;
    }
    //.iot {
    //  width: 209rpx;
    //  height: 343rpx;
    //  position: absolute;
    //  left: 446rpx;
    //  top: 64rpx;
    //}
  }
  .expireDeviceBox {
    font-size: 28rpx;
    color: rgba(13, 13, 13, 0.9);
    background: linear-gradient(155deg, #afb9f9 0%, white 45%);
    border-radius: 40rpx;
    .expireDeviceBoxTitle {
      text-align: center;
      margin-top: 10rpx;
      margin-bottom: 30rpx;
      font-size: 34rpx;
      font-weight: 700;
    }

    .expireDeviceBoxBottomBox {
      display: flex;
      justify-content: space-between;
      font-size: $f-base;
      .expireDeviceBoxButtomBox-2 {
        text-align: center;
        padding:10rpx 0 40rpx 0;
        flex: 1;
        color: $u-primary;
      }
      .expireDeviceBoxButtomBox {
        text-align: center;
        padding:10rpx 0 40rpx 0;
        flex: 1;
      }
    }
  }
</style>
